package exceptions.Handler;

import com.alibaba.fastjson.JSONObject;
import constants.enums.Error;
import exceptions.service.ServiceRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 针对于前端的异常处理
 */

public class ExceptionHandler extends SimpleMappingExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class);

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
                                              Exception ex) {
        ModelAndView mv = super.doResolveException(request, response, handler, ex);
        String url = request.getRequestURI();
        logger.error("controller error.url=" + url, ex);
        /* 使用response返回 */
        response.setStatus(HttpStatus.OK.value()); // 设置状态码
        response.setContentType(MediaType.APPLICATION_JSON_VALUE); // 设置ContentType
        response.setCharacterEncoding("UTF-8"); // 避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        Map<String, Object> map = new HashMap<>();
        map.put(Error.SYS_ERROR.getCode().toString(), Error.SYS_ERROR.getMsg());
        if (ex instanceof ServiceRuntimeException) {
            map.clear();
            ServiceRuntimeException serviceException = (ServiceRuntimeException) ex;
            String code = serviceException.getCode();
            String message = serviceException.getMessage();
            map.put(code, message);
        }
        try {
            PrintWriter printWriter = response.getWriter();
            printWriter.write(JSONObject.toJSONString(map));
            printWriter.flush();
            printWriter.close();
        } catch (IOException e) {
            logger.error("与客户端通讯异常:" + e.getMessage(), e);
        }
        logger.error("异常:" + ex.getMessage(), ex);
        return mv;
    }
}

